use std::process::Command;
use std::process::Stdio;

use opencv::prelude::*;
use opencv::videoio;
use opencv::videoio::VideoCaptureProperties;
use video_img_find::{img, video_cap};

const VIDEO_PATH: &str = "/home/jaakan/下载/超级飞侠9/15.mp4";

#[test]
fn find_img() -> anyhow::Result<()> {
    let target = img::read_img_mat_from_path("./target.jpg")?;
    let target_hash = img::img_hash_str(&target)?;

    let mut video_cap = video_cap::open_video_cap(VIDEO_PATH)?;
    let opened = videoio::VideoCapture::is_opened(&video_cap)?;
    if !opened {
        panic!("Unable to open default camera!");
    }

    // 跳过时间
    let skip_ms = 60_000f64;
    video_cap::set_cap_pos_ms(&mut video_cap, skip_ms)?;

    // 帧率
    // let fps = video_cap::get_cap_prop(&video_cap, VideoCaptureProperties::CAP_PROP_FPS)?;

    let mut frame = Mat::default();
    let mut key_vals = Vec::<(f64, f64)>::new();

    for i in 0.. {
        let grab = match video_cap.grab() {
            Err(err) => {
                eprintln!("ERR:{}", err);
                false
            }
            Ok(grab) => grab,
        };

        if !grab {
            println!("===== END ======");
            video_cap.release().unwrap();
            break;
        }

        // 每10帧处理一次
        if i % 10 != 0 {
            continue;
        }

        video_cap::read_frame(&mut video_cap, &mut frame)?;
        let hash = img::img_hash_str(&frame)?;
        let score = img::cmp_img_hash(&target_hash, &hash)?;

        let pos_ms = video_cap::get_curr_pos_ms(&video_cap)?;
        println!("每10帧处理一次. 当前时间:{}, 相似值:{}", pos_ms, score,);

        let mut match_num = 0;
        if score > 0.90f32 {
            key_vals.push((pos_ms, score as f64));
            println!("找到关键帧{}", pos_ms);
            let path = format!("./tmp/found_out_{}.jpg", i);
            img::save_rgb_img_width_frame(&path, &frame)?;

            match_num += 1;
            if match_num > 5 {
                break;
            }
        }
    }

    println!("{:?}", key_vals);

    Ok(())
}

#[test]
fn test2() {
    println!("{}", (85_023f64 % 15_000f64));
}

#[test]
fn out_img() -> anyhow::Result<()> {
    let mut video_cap = video_cap::open_video_cap(VIDEO_PATH)?;
    let opened = videoio::VideoCapture::is_opened(&video_cap).unwrap();
    if !opened {
        panic!("Unable to open default camera!");
    }

    // 跳过时间
    let skip_ms = 600_000f64;
    video_cap::set_cap_pos_ms(&mut video_cap, skip_ms)?;

    for i in 0..20 {
        for _ in 0..10 {
            video_cap::next_frame(&mut video_cap).unwrap();
        }
        let mut frame = Mat::default();
        video_cap::read_frame(&mut video_cap, &mut frame)?;
        let path = format!("./out/{}.jpg", i);
        img::save_rgb_img_width_frame(&path, &frame)?;
    }

    video_cap.release().unwrap();
    Ok(())
}

#[test]
fn test_command() {
    let cmd = "echo '12344555' >> ./tmp/commands.sh";

    let output = Command::new("bash")
        .arg("-c")
        .arg(cmd)
        .output()
        .expect("Failed to execute command");

    println!("{output:?}");
}
